//
//  MainViewController.m
//  Pegasus
//
//  Created by pegasus_cpp on 14-7-14.
//  Copyright (c) 2014年 yandx. All rights reserved.
//

#import "MainViewController.h"

@interface MainViewController ()

@end

@implementation MainViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationItem.title = @"点快餐";
    
    aMapView = [[MAMapView alloc] initWithFrame:self.view.frame];
    aMapView.delegate = self;
    [self.view addSubview:aMapView];
    [aMapView setUserTrackingMode:MAUserTrackingModeFollow];
    aMapView.showsUserLocation = YES;
    [aMapView setZoomLevel:15 animated:YES];
    
    isSearching = NO;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)searchRestaurants {
    
    if (!search) {
        search = [[AMapSearchAPI alloc] initWithSearchKey:kGdKey Delegate:self];
    }
    
    AMapPlaceSearchRequest *poiRequest = [[AMapPlaceSearchRequest alloc] init];
    poiRequest.searchType = AMapSearchType_PlaceAround;
    poiRequest.keywords = @"快餐";
    poiRequest.location = [AMapGeoPoint locationWithLatitude:lat longitude:lng];
    poiRequest.radius = 1000;
    [search AMapPlaceSearch:poiRequest];
}

- (void)dropRestaurants {
    if (!anoArr) anoArr = [[NSMutableArray alloc] init];
    [aMapView removeAnnotations:anoArr];
    
    for (PoiModel *model in poiArr) {
        if (model) {
            MAPointAnnotation *annotation = [[MAPointAnnotation alloc] init];
            annotation.coordinate = CLLocationCoordinate2DMake([model.lat floatValue], [model.lng floatValue]);
            annotation.title = model.name;
            annotation.subtitle = model.tel;
            [anoArr addObject:annotation];
        }
    }
    
    if (anoArr.count > 0) {
        [aMapView addAnnotations:anoArr];
    }
}

#pragma mark -AMapSearchDelegate
- (void)onPlaceSearchDone:(AMapPlaceSearchRequest *)request response:(AMapPlaceSearchResponse *)response {
    
    if (!poiArr) poiArr = [[NSMutableArray alloc] init];
    if (response.pois.count > 0) {
        [poiArr removeAllObjects];
    }
    
    for (AMapPOI *p in response.pois) {
        NSLog(@"poi => %@", p.description);
        
        if (p.tel.length > 0) {
            
            PoiModel *model = [[PoiModel alloc] init];
            model.name = [NSString stringWithFormat:@"%@", p.name];
            model.addr = [NSString stringWithFormat:@"%@", p.address];
            model.lat = [NSString stringWithFormat:@"%lf", p.location.latitude];
            model.lng = [NSString stringWithFormat:@"%lf", p.location.longitude];
            model.tel = [NSString stringWithFormat:@"%@", p.tel];
            
            [poiArr addObject:model];
        }
    }
    
    if (poiArr.count > 0) {
        
        [self dropRestaurants];
    }
}

- (IBAction)callRestaurant:(id)sender {
    UIButton *btn = (UIButton *)sender;
    
    NSLog(@"callRestaurant tag => %d", btn.tag);
    
    if (btn.tag < poiArr.count) {
        PoiModel *model = [poiArr objectAtIndex:btn.tag];
        if (model) {
            NSLog(@"callRestaurant name => %@   tel => %@", model.name, model.tel);
            
            if (!phoneArr) phoneArr = [[NSMutableArray alloc] init];
            [phoneArr removeAllObjects];
            
            NSString *tel = model.tel;
            NSRange range = [tel rangeOfString:@";"];
            if (range.location != NSNotFound) {
                phoneArr = [[NSMutableArray alloc] initWithArray:[tel componentsSeparatedByString:@";"]];
            } else {
                [phoneArr addObject:tel];
            }
            
            // 添加电话
            UIActionSheet *sheet = [[UIActionSheet alloc] init];
            [sheet setTitle:@"电话订餐"];
            for (NSString *phone in phoneArr) {
                [sheet addButtonWithTitle:phone];
            }
            [sheet addButtonWithTitle:@"取消"];
            sheet.delegate = self;
            [sheet showInView:self.view];
        }
    }
}

#pragma mark -MAMapViewDelegate
- (void)mapView:(MAMapView *)mapView didUpdateUserLocation:(MAUserLocation *)userLocation {
    NSLog(@"didUpdateUserLocations => %lf  %lf", userLocation.location.coordinate.latitude, userLocation.location.coordinate.longitude);
    
    if (isSearching) return ;
    isSearching = YES;
    
    lat = userLocation.location.coordinate.latitude;
    lng = userLocation.location.coordinate.longitude;
    
    [self searchRestaurants];
}

- (MAAnnotationView *)mapView:(MAMapView *)mapView viewForAnnotation:(id<MAAnnotation>)annotation {
    if ([annotation isKindOfClass:[MAPointAnnotation class]]) {
        static NSString *pointReuseIndetifier = @"pointReuseIndetifier";
        MAPinAnnotationView*annotationView = (MAPinAnnotationView*)[mapView dequeueReusableAnnotationViewWithIdentifier:pointReuseIndetifier];
        if (annotationView == nil)
        {
            annotationView = [[MAPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:pointReuseIndetifier];
            annotationView.canShowCallout= YES;      //设置气泡可以弹出，默认为NO
            annotationView.animatesDrop = YES;       //设置标注动画显示，默认为NO
            annotationView.draggable = YES;           //设置标注可以拖动，默认为NO
            UIButton *btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            
            MAPointAnnotation *pointAnnotation = (MAPointAnnotation *)annotation;
            NSInteger tag = -1;
            for (int i = 0; i < poiArr.count; i ++) {
                PoiModel *model = [poiArr objectAtIndex:i];
                if (model && [model.name isEqualToString:pointAnnotation.title]) {
                    tag = i; break;
                }
            }
            
            btn.tag = tag;
            [btn addTarget:self action:@selector(callRestaurant:) forControlEvents:UIControlEventTouchUpInside];
            
            annotationView.rightCalloutAccessoryView = btn;
        }
        annotationView.pinColor = [anoArr indexOfObject:annotation];
        return annotationView;
    }
    return nil;
}

- (void)mapView:(MAMapView *)mapView didSelectAnnotationView:(MAAnnotationView *)view {
    MAPointAnnotation *pointAnnotation = view.annotation;
    NSLog(@"didSelectAnnotationView title => %@", pointAnnotation.title);
}

#pragma mark -UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    NSLog(@"buttonIndex => %d", buttonIndex);
    if (buttonIndex < phoneArr.count) {
        NSString *phone = [phoneArr objectAtIndex:buttonIndex];
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel://%@", phone]]];
    }
}
@end














































